import { getDailyMeals, deleteMealRecord } from '@/api/meals'
import request from '@/config/axios'

const state = {
  mealRecords: [],
  loading: false,
  error: null
}

const mutations = {
  SET_MEAL_RECORDS(state, records) {
    console.log('Setting meal records:', records)
    state.mealRecords = records
  },
  REMOVE_MEAL_RECORD(state, recordId) {
    state.mealRecords = state.mealRecords.filter(record => record.recordId !== recordId)
  },
  SET_LOADING(state, status) {
    state.loading = status
  },
  SET_ERROR(state, error) {
    state.error = error
  }
}

const actions = {
  async fetchDailyMeals({ commit }, { date, userId }) {
    commit('SET_LOADING', true)
    try {
      const response = await getDailyMeals({ date, userId })
      console.log('API Response:', response)
      
      if (!response || typeof response !== 'object') {
        throw new Error('Invalid response format')
      }

      if (Array.isArray(response)) {
        console.log('Direct array response:', response)
        commit('SET_MEAL_RECORDS', response)
        return
      }

      if (response.data) {
        if (Array.isArray(response.data)) {
          console.log('Array in data field:', response.data)
          commit('SET_MEAL_RECORDS', response.data)
          return
        }
        
        if (response.data.success && Array.isArray(response.data.data)) {
          console.log('Standard response format:', response.data.data)
          commit('SET_MEAL_RECORDS', response.data.data)
          return
        }
      }

      console.warn('Unrecognized API response format:', response)
      commit('SET_ERROR', '接口返回格式错误')
      commit('SET_MEAL_RECORDS', [])
    } catch (error) {
      console.error('获取膳食记录失败:', error)
      commit('SET_ERROR', '获取膳食记录失败')
      commit('SET_MEAL_RECORDS', [])
    } finally {
      commit('SET_LOADING', false)
    }
  },
  async addMealRecord(_, record) {
    try {
      const formattedRecord = {
        ...record,
        recordTime: record.recordTime + ':00',
        details: record.details || []
      }

      const response = await request({
        url: '/api/meal-records',
        method: 'post',
        data: formattedRecord
      })

      if (response?.success) {
        return response.data
      } else {
        throw new Error(response?.message || '添加失败')
      }
    } catch (error) {
      console.error('添加膳食记录失败:', error)
      throw error
    }
  },
  async deleteMealRecord({ commit }, { recordId, userId }) {
    try {
      const response = await deleteMealRecord(recordId, userId)
      
      if (response?.code === 200 && response?.success) {
        commit('REMOVE_MEAL_RECORD', recordId)
        return true
      } else {
        return false
      }
    } catch (error) {
      console.error('删除膳食记录失败:', error)
      throw error
    }
  }
}

const getters = {
  getMealRecords: state => {
    console.log('Getter getMealRecords called with:', state.mealRecords)
    return Array.isArray(state.mealRecords) ? state.mealRecords : []
  },
  isLoading: state => state.loading,
  getError: state => state.error
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
} 